package org.example.shop.service;

import org.example.shop.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {
    @Autowired
    private RedisTemplate redisTemplate;

    private static final String GOODS_PAGE_KEY = "goods:page:"; // 商品分页数据的键前缀
    private static final long CACHE_EXPIRE_TIME = 1; // 缓存过期时间（分钟）

    // 缓存商品分页数据
    public void cacheGoodsPage(int page, List<Goods> goods) {
        String key = GOODS_PAGE_KEY + page;
        redisTemplate.opsForValue().set(key, goods, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
    }

    // 获取缓存商品分页数据
    public List<Goods> getCacheGoodsPage(int page) {
        String key = GOODS_PAGE_KEY + page;
        return (List<Goods>) redisTemplate.opsForValue().get(key);
    }

    // 删除缓存商品分页数据
    public void delCacheGoodsPage(int page) {
        String key = GOODS_PAGE_KEY + page;
        redisTemplate.delete(key);
    }

    // 删除所有商品分页缓存
    public void deleteCacheGoodsPage(int totalPage) {
        for (int i = 0; i < totalPage; i++) {
            String key = GOODS_PAGE_KEY + i;
            redisTemplate.delete(key);
        }
    }
}